package admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import service.PutCache;
import service.Util;

import model.Category;
import model.News;
import model.NewsRecent;
import model.Tags;

import com.google.appengine.api.datastore.Text;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class PostNewsServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String title = req.getParameter("post[title]");
		String category = req.getParameter("post[tag]");
		if(category.equals(""))
			category = "Chuyên mục khác";
		category = category.replaceAll(",[\\w\\W]$", "");
		String source = "";
		String content = req.getParameter("post[content]");
		
		Document doc = Jsoup.parse(content);
		Elements elements = doc.select("img");
		String thumb = "/images/thumb.png";
		try {
			source = doc.select("a").last().attr("href");
		} catch (Exception e) {
			// TODO: handle exception
		}
		String ct = doc.select("body").html().trim();
		if(elements.size()>0)
		{
			for (int i = 0; i < elements.size(); i++) {
				ct = ct.replace(elements.get(i).toString(), "<div class='image'>"+elements.get(i).toString()+"</div>");
			}
			thumb = elements.get(0).attr("src");
		}
		
		try {
			ObjectifyService.register(Category.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Objectify objectify2 = ObjectifyService.begin();
		
		try {
			Category cate = objectify2.get(new Key<Category>(Category.class, Util.convertAlias(category)));
		} catch (Exception e) {
			Category cate = new Category();
			cate.setAlias(Util.convertAlias(category));
			cate.setName(category);
			objectify2.put(cate);
		}
		
		String tag = Util.keyword(doc.text());
		String[] listTag = tag.split(",");
		ArrayList<String> tagers = new ArrayList<String>();
		
		try {
			ObjectifyService.register(Tags.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Objectify objectify1 = ObjectifyService.begin();
		
		for (int i = 0; i < listTag.length; i++) {
			if(!listTag[i].trim().equals(""))
			{
				tagers.add(listTag[i]);
				
				PutCache.putCacheList(listTag[i], "newTag", 50);
				
				try {
					Tags tagDetail = objectify1.get(new Key<Tags>(Tags.class, Util.convertAlias(listTag[i])));
					tagDetail.addListnews(title+"|"+Util.cutDescription(doc.text())+"|"+String.valueOf(new Date().getTime())+"|"+thumb);
//					tagDetail.addListDes(Util.cutDescription(doc.text()));
//					tagDetail.addListDate(String.valueOf(new Date().getTime()));
//					tagDetail.addListThumb(thumb);
					objectify1.put(tagDetail);
				} catch (Exception e) {
					Tags tagDetail = new Tags();
					tagDetail.setAlias(Util.convertAlias(listTag[i]));
					tagDetail.setName(listTag[i]);
					tagDetail.addListnews(title+"|"+Util.cutDescription(doc.text()).replace("|", " ")+"|"+String.valueOf(new Date().getTime())+"|"+thumb);
//					tagDetail.addListDes(Util.cutDescription(doc.text()));
//					tagDetail.addListDate(String.valueOf(new Date().getTime()));
//					tagDetail.addListThumb(thumb);
					objectify1.put(tagDetail);
				}
			}
		}
		
		
		try {
			ObjectifyService.register(News.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Objectify objectify = ObjectifyService.begin();
		
		News news = new News();
		news.setAlias(Util.convertAlias(title));
		news.setCategory(category);
		news.setCategoryAlias(Util.convertAlias(category));
		news.setContent(new Text(Util.cleanContent(ct)));
		news.setSource(new Text(source));
		news.setTitle(new Text(title));
		news.setThumb(thumb);
		news.setTag(tagers);
		
		objectify.put(news);
		
		ArrayList<NewsRecent> newCategory = PutCache.getCacheNews("list"+Util.convertAlias(category)+"1");
		if(newCategory.size()>0)
		{
			NewsRecent newsRecent = new NewsRecent();
			newsRecent.setDate(news.getDate());
			newsRecent.setThumb(news.getThumb());
			newsRecent.setTitle(news.getTitle().getValue());
			newsRecent.setCategory(news.getCategory());
			newsRecent.setDes(Util.cutDescription(news.getContent().getValue()));
			
			PutCache.putCacheNews(newsRecent, "list"+Util.convertAlias(category)+"1", 20);
		}
		
		ArrayList<NewsRecent> cacheCcategory = PutCache.getCacheNews(Util.convertAlias(category));
		if(cacheCcategory.size()>0)
		{
			NewsRecent newsRecent = new NewsRecent();
			newsRecent.setDate(news.getDate());
			newsRecent.setThumb(news.getThumb());
			newsRecent.setTitle(news.getTitle().getValue());
			newsRecent.setCategory(news.getCategory());
			newsRecent.setDes(Util.cutDescription(news.getContent().getValue()));
			
			PutCache.putCacheNews(newsRecent, Util.convertAlias(category), 5);
		}
		
		ArrayList<NewsRecent> newUpdate = PutCache.getCacheNews("newUpdate");
	
		if(newUpdate.size()>0)
		{
			NewsRecent newsRecent = new NewsRecent();
			newsRecent.setDate(news.getDate());
			newsRecent.setThumb(news.getThumb());
			newsRecent.setTitle(news.getTitle().getValue());
			newsRecent.setCategory(news.getCategory());
			newsRecent.setDes(Util.cutDescription(news.getContent().getValue()));
			
			PutCache.putCacheNews(newsRecent, "newUpdate", 15);
		}
		
		ArrayList<String> footerCate = PutCache.getCacheList("footerCate");
		if(footerCate.size()>0)
		{
			PutCache.putCacheList(news.getCategory(), "footerCate", 59);
		}
		
		resp.getWriter().println("1");
	}
}
